<template>
  <div class="min-h-screen bg-gray-50 py-8">
    <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
      <!-- 页面标题 -->
      <div class="mb-8">
        <h1 class="text-3xl font-bold text-gray-900">章节配置管理</h1>
        <p class="mt-2 text-gray-600">配置每章的学习材料、权重分值和显示设置</p>
      </div>

      <!-- 操作按钮 -->
      <div class="mb-6 flex justify-between items-center">
        <div class="flex space-x-4">
          <button
            @click="showCreateModal = true"
            class="bg-blue-600 text-white px-4 py-2 rounded-lg hover:bg-blue-700 transition-colors flex items-center space-x-2"
          >
            <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 6v6m0 0v6m0-6h6m-6 0H6"></path>
            </svg>
            <span>新增章节</span>
          </button>
          <button
            @click="loadConfigs"
            class="bg-gray-600 text-white px-4 py-2 rounded-lg hover:bg-gray-700 transition-colors flex items-center space-x-2"
          >
            <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"></path>
            </svg>
            <span>刷新</span>
          </button>
        </div>
      </div>

      <!-- 加载状态 -->
      <div v-if="loading" class="flex justify-center items-center py-12">
        <div class="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600"></div>
        <span class="ml-2 text-gray-600">加载中...</span>
      </div>

      <!-- 错误信息 -->
      <div v-if="error" class="bg-red-50 border border-red-200 rounded-lg p-4 mb-6">
        <div class="flex items-center">
          <svg class="w-5 h-5 text-red-400 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"></path>
          </svg>
          <span class="text-red-800">{{ error }}</span>
        </div>
      </div>

      <!-- 章节配置列表 -->
      <div v-if="!loading && configs.length > 0" class="bg-white shadow-lg rounded-lg overflow-hidden">
        <div class="overflow-x-auto">
          <table class="min-w-full divide-y divide-gray-200">
            <thead class="bg-gray-50">
              <tr>
                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">章节</th>
                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">标题</th>
                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">状态</th>
                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">学习材料</th>
                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">更新时间</th>
                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">操作</th>
              </tr>
            </thead>
            <tbody class="bg-white divide-y divide-gray-200">
              <tr v-for="config in paginatedConfigs" :key="config.id" class="hover:bg-gray-50">
                <td class="px-6 py-4 whitespace-nowrap">
                  <div class="text-sm font-medium text-gray-900">第{{ config.chapterNumber }}章</div>
                </td>
                <td class="px-6 py-4">
                  <div class="text-sm text-gray-900">{{ config.title }}</div>
                  <div class="text-sm text-gray-500">{{ config.description }}</div>
                </td>
                <td class="px-6 py-4 whitespace-nowrap">
                  <span :class="config.isEnabled ? 'bg-green-100 text-green-800' : 'bg-red-100 text-red-800'" 
                        class="inline-flex px-2 py-1 text-xs font-semibold rounded-full">
                    {{ config.isEnabled ? '启用' : '禁用' }}
                  </span>
                </td>
                <td class="px-6 py-4">
                  <div class="text-sm text-gray-900">
                    <div class="flex flex-wrap gap-1">
                      <span v-if="config.lecture?.uploadedFiles?.length" class="bg-blue-100 text-blue-800 px-2 py-1 rounded text-xs">
                        讲义 ({{ config.lecture.uploadedFiles.length }})
                      </span>
                      <span v-if="config.slides?.uploadedFiles?.length" class="bg-green-100 text-green-800 px-2 py-1 rounded text-xs">
                        课件 ({{ config.slides.uploadedFiles.length }})
                      </span>
                      <span v-if="config.video?.uploadedFiles?.length" class="bg-purple-100 text-purple-800 px-2 py-1 rounded text-xs">
                        视频 ({{ config.video.uploadedFiles.length }})
                      </span>
                      <span v-if="config.examples?.uploadedFiles?.length" class="bg-yellow-100 text-yellow-800 px-2 py-1 rounded text-xs">
                        示例 ({{ config.examples.uploadedFiles.length }})
                      </span>
                      <span v-if="config.practice?.uploadedFiles?.length" class="bg-orange-100 text-orange-800 px-2 py-1 rounded text-xs">
                        实践 ({{ config.practice.uploadedFiles.length }})
                      </span>
                      <span v-if="config.assignment?.uploadedFiles?.length" class="bg-red-100 text-red-800 px-2 py-1 rounded text-xs">
                        作业 ({{ config.assignment.uploadedFiles.length }})
                      </span>
                    </div>
                  </div>
                </td>
                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                  {{ config.updatedAt ? formatDate(config.updatedAt) : '-' }}
                </td>
                <td class="px-6 py-4 whitespace-nowrap text-sm font-medium">
                  <div class="flex space-x-2">
                    <button
                      @click="editConfig(config)"
                      class="text-blue-600 hover:text-blue-900 transition-colors"
                    >
                      编辑
                    </button>
                    <button
                      @click="toggleStatus(config)"
                      :class="config.isEnabled ? 'text-red-600 hover:text-red-900' : 'text-green-600 hover:text-green-900'"
                      class="transition-colors"
                    >
                      {{ config.isEnabled ? '禁用' : '启用' }}
                    </button>
                    <button
                      @click="deleteConfig(config)"
                      class="text-red-600 hover:text-red-900 transition-colors"
                    >
                      删除
                    </button>
                  </div>
                </td>
              </tr>
            </tbody>
          </table>
        </div>
      </div>

      <!-- 分页 -->
      <div v-if="!loading && configs.length > 0 && totalPages > 1" class="mt-6 flex justify-center">
        <nav class="flex items-center gap-2">
          <button
            @click="currentPage = Math.max(1, currentPage - 1)"
            :disabled="currentPage === 1"
            class="px-3 py-2 text-sm font-medium text-gray-500 bg-white border border-gray-300 rounded-md hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
          >
            上一页
          </button>
          
          <span class="px-3 py-2 text-sm text-gray-700">
            第 {{ currentPage }} 页，共 {{ totalPages }} 页
          </span>
          
          <button
            @click="currentPage = Math.min(totalPages, currentPage + 1)"
            :disabled="currentPage === totalPages"
            class="px-3 py-2 text-sm font-medium text-gray-500 bg-white border border-gray-300 rounded-md hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
          >
            下一页
          </button>
        </nav>
      </div>

      <!-- 空状态 -->
      <div v-if="!loading && configs.length === 0" class="text-center py-12">
        <svg class="mx-auto h-12 w-12 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
          <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"></path>
        </svg>
        <h3 class="mt-2 text-sm font-medium text-gray-900">暂无章节配置</h3>
        <p class="mt-1 text-sm text-gray-500">开始创建第一个章节配置</p>
        <div class="mt-6">
          <button
            @click="showCreateModal = true"
            class="bg-blue-600 text-white px-4 py-2 rounded-lg hover:bg-blue-700 transition-colors"
          >
            新增章节
          </button>
        </div>
      </div>
    </div>

    <!-- 创建/编辑模态框 -->
    <ChapterConfigModal
      v-if="showCreateModal || showEditModal"
      :visible="showCreateModal || showEditModal"
      :config="editingConfig || undefined"
      :is-edit="showEditModal"
      @close="closeModal"
      @save="handleSave"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useAuthStore } from '@/stores/auth'
import ChapterConfigModal from '@/components/ChapterConfigModal.vue'

// 从环境变量获取 API 基础地址
const API_BASE_URL = `http://${import.meta.env.VITE_BACKEND_HOST}:${import.meta.env.VITE_BACKEND_PORT}`

interface UploadedFile {
  filename: string
  originalName: string
  size: number
  url: string
  path: string
}

interface MaterialConfigType {
  weight: number
  isRequired?: boolean
  allowDownload?: boolean
  duration?: number
  deadline?: string
  description?: string
  uploadedFiles?: UploadedFile[]
}

interface ChapterConfig {
  id?: number
  chapterNumber: number
  title: string
  description: string
  isEnabled: boolean
  lecture?: MaterialConfigType
  slides?: MaterialConfigType
  video?: MaterialConfigType
  examples?: MaterialConfigType
  practice?: MaterialConfigType
  assignment?: MaterialConfigType
  createdAt?: string
  updatedAt?: string
}

const authStore = useAuthStore()
const configs = ref<ChapterConfig[]>([])
const loading = ref(false)
const error = ref('')
const showCreateModal = ref(false)
const showEditModal = ref(false)
const editingConfig = ref<ChapterConfig | null>(null)

// 分页
const currentPage = ref(1)
const pageSize = ref(10)

// 分页相关计算属性
const totalPages = computed(() => {
  return Math.ceil(configs.value.length / pageSize.value)
})

const paginatedConfigs = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return configs.value.slice(start, end)
})

// 加载章节配置
const loadConfigs = async () => {
  loading.value = true
  error.value = ''
  
  try {
    const response = await fetch(`${API_BASE_URL}/api/chapter-config`, {
      headers: {
        'Authorization': `Bearer ${authStore.token}`,
        'Content-Type': 'application/json'
      }
    })
    
    if (!response.ok) {
      throw new Error('获取章节配置失败')
    }
    
    const data = await response.json()
    // 转换后端数据格式为前端期望的格式
    configs.value = (data.data || []).map((config: any) => ({
      id: config.id,
      chapterNumber: config.chapterNumber,
      title: config.chapterTitle,
      description: config.chapterDescription,
      isEnabled: config.isActive,
      lecture: config.docxConfig ? {
        uploadedFiles: config.docxConfig.uploadedFiles || [],
        weight: config.docxConfig.weight || 0,
        enabled: config.docxConfig.enabled,
        isRequired: config.docxConfig.isRequired,
        allowDownload: config.docxConfig.allowDownload
      } : undefined,
      slides: config.pptxConfig ? {
        uploadedFiles: config.pptxConfig.uploadedFiles || [],
        weight: config.pptxConfig.weight || 0,
        enabled: config.pptxConfig.enabled,
        isRequired: config.pptxConfig.isRequired,
        allowDownload: config.pptxConfig.allowDownload
      } : undefined,
      video: config.videosConfig ? {
          uploadedFiles: config.videosConfig.uploadedFiles || [],
          weight: config.videosConfig.weight || 0,
          enabled: config.videosConfig.enabled,
          isRequired: config.videosConfig.isRequired,
          allowDownload: config.videosConfig.allowDownload,
          duration: config.videosConfig.duration
        } : undefined,
        examples: config.examplesConfig ? {
          uploadedFiles: config.examplesConfig.uploadedFiles || [],
          weight: config.examplesConfig.weight || 0,
          enabled: config.examplesConfig.enabled,
          isRequired: config.examplesConfig.isRequired,
          allowDownload: config.examplesConfig.allowDownload
      } : undefined,
      practice: config.practiceConfig ? {
        uploadedFiles: config.practiceConfig.uploadedFiles || [],
        weight: config.practiceConfig.weight || 0,
        enabled: config.practiceConfig.enabled,
        isRequired: config.practiceConfig.isRequired,
        allowDownload: config.practiceConfig.allowDownload
      } : undefined,
      assignment: config.assignmentsConfig ? {
          uploadedFiles: config.assignmentsConfig.uploadedFiles || [],
          weight: config.assignmentsConfig.weight || 0,
          enabled: config.assignmentsConfig.enabled,
          isRequired: config.assignmentsConfig.isRequired,
          allowDownload: config.assignmentsConfig.allowDownload,
          deadline: config.assignmentsConfig.deadline
      } : undefined,
      createdAt: config.createdAt,
      updatedAt: config.updatedAt
    }))
  } catch (err) {
    error.value = err instanceof Error ? err.message : '获取章节配置失败'
    console.error('Error loading chapter configs:', err)
  } finally {
    loading.value = false
  }
}

// 编辑配置
const editConfig = (config: ChapterConfig) => {
  editingConfig.value = { ...config }
  showEditModal.value = true
}

// 切换启用状态
const toggleStatus = async (config: ChapterConfig) => {
  try {
    const response = await fetch(`${API_BASE_URL}/api/chapter-config/${config.id}`, {
      method: 'PUT',
      headers: {
        'Authorization': `Bearer ${authStore.token}`,
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        chapterNumber: config.chapterNumber,
        chapterTitle: config.title,
        chapterDescription: config.description,
        isActive: !config.isEnabled
      })
    })
    
    if (!response.ok) {
      throw new Error('更新状态失败')
    }
    
    await loadConfigs()
  } catch (err) {
    error.value = err instanceof Error ? err.message : '更新状态失败'
  }
}

// 删除配置
const deleteConfig = async (config: ChapterConfig) => {
  if (!confirm(`确定要删除第${config.chapterNumber}章的配置吗？`)) {
    return
  }
  
  try {
    const response = await fetch(`${API_BASE_URL}/api/chapter-config/${config.id}`, {
      method: 'DELETE',
      headers: {
        'Authorization': `Bearer ${authStore.token}`
      }
    })
    
    if (!response.ok) {
      throw new Error('删除配置失败')
    }
    
    await loadConfigs()
  } catch (err) {
    error.value = err instanceof Error ? err.message : '删除配置失败'
  }
}

// 关闭模态框
const closeModal = () => {
  showCreateModal.value = false
  showEditModal.value = false
  editingConfig.value = null
}

// 保存配置
const handleSave = async (result: any) => {
  await loadConfigs()
  closeModal()
}

// 格式化日期
const formatDate = (dateString: string) => {
  return new Date(dateString).toLocaleString('zh-CN')
}

// 组件挂载时加载数据
onMounted(() => {
  loadConfigs()
})
</script>

<style scoped>
/* 组件特定样式 */
</style>